﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Popup.Master" AutoEventWireup="true"
    CodeBehind="Item-Property-Link.aspx.cs" Inherits="PromotionEngine.Item_Property_Link" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <script type="text/javascript">
        var oItemPropertyLink = {};
        var oItem = {};
        var oItemPropertyDetail = {};
        var isInsert = false;
        var gird;
        var girdDetail;
        var propertyForDetailID = 0;
             var checkedIds = {};
           var itemID  = 0;
                var referenceName;
           function closeLink()
           {
           parent.$("#details").data("kendoWindow").close();
           }
           
        //Get All Customer
        function GetCustomerPropertyDetails() {
            $.ajax({
                type: "GET",
                url: "Item-Property.aspx/GetAllItemPropertyDetails",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oCustomerPropertyDetail = response.d.Data;

                },
                failure: function (response) {
                    alert(response.d);
                },
                 error: function (jqXHR, textStatus, errorThrown) {
                            if (jqXHR.status == 500) {
                                alert('Internal error: ' + jqXHR.responseText);
                            } else {
                                alert('Unexpected error.' + jqXHR.responseText);
                            }
                        }
            });
        }
         function updateLink()
         {
                var checked = this.checked,
                row = $(this).closest("tr"),
                dataItem = gridDetail.dataItem(row);
                checkedIds[dataItem.id] = checked;
                if (checked) {
            row.addClass("k-state-selected");

                    isInsert =true;
                    } else {
                      isInsert =false;
            row.removeClass("k-state-selected");
                }
               var items = $("#gridDetail").data("kendoGrid").dataSource.data();
                  dataItem.set('PropertyLinkID', checked);
                oItemPropertyLink.ItemID = itemID;
                oItemPropertyLink.PropertyDetailID = dataItem.PropertyDetailID;
                 //Update or Insert
                    UpdatePropertyLink(isInsert);
         }
          function updateRadio(e)
         {
                //Delete All
                 row = $(e).closest("tr");
                  var dataItem = gridDetail.dataItem(row);
               var oTest=[];
                     var items = gridDetail.dataSource.data();
                    for (i = 0; i < items.length; i++) {
                      oItemPropertyLink = {};
                        var item = items[i];
                        isInsert = false;   
                    oItemPropertyLink.ItemID = itemID;
                    oItemPropertyLink.PropertyDetailID = item.PropertyDetailID
                    oTest.push(oItemPropertyLink);
                     item.set('PropertyLinkID', '');
                  }
                        $.ajax({
                        type: "POST",
                      url: "Item-Property-Link.aspx/UpdateItemPropertyLinks",
                        data: JSON.stringify({
                            oItemPropertyLink: JSON.stringify(oTest),
                            isInsert: false
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                        //Insert new 
                         var checked = e.checked;
                         row.addClass("k-state-selected");
                         isInsert = true;
                         dataItem.set('PropertyLinkID', checked);
                         oItemPropertyLink.ItemID = itemID;
                         oItemPropertyLink.PropertyDetailID = dataItem.PropertyDetailID;
                         //Update or Insert
                         UpdatePropertyLink(isInsert);
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
         }
        //Load Detail
        function onChange(arg) {
         var selectedRows = this.select();
            var selectedDataItems = [];
            for (var i = 0; i < selectedRows.length; i++) {
              var dataItem = this.dataItem(selectedRows[i]);
              selectedDataItems.push(dataItem);
            }
            //Set ID
            propertyForDetailID = selectedDataItems[0].PropertyID;
            itemID = $('#<%=lblItemID.ClientID%>').val();
              referenceName =selectedDataItems[0].ReferenceName; 
             
             //Load Grid
             var headerTemplate='<input type="checkbox" id="checkAll" onclick="updateAll(this)"/>';
             var template="<input type='checkbox'  class='check-box'  #= PropertyLinkID ? 'checked=checked' : '' # enabled='' />";
            if(referenceName == 'Single Value')
             {
               headerTemplate='';
               template="<input type='radio' name='link'  class='radio-box' onchange='updateRadio(this)'  #= PropertyLinkID ? 'checked=checked' : '' # enabled='' />";
             }
             else if(referenceName == 'Multi Value')
             {
                  headerTemplate='<input type="checkbox" id="checkAll" onclick="updateAll(this)"/>'; 
            
             }
             else if(referenceName = 'Free Text')
             {

             }
               var columnsConfig = [];
                columnsConfig.push({ title: '', headerTemplate: headerTemplate, template: template ,width:50 });
                            columnsConfig.push({ field: "PropertyDetailID", title: "Property Detail ID", width: 100, hidden: true });
                             columnsConfig.push({ field: "PropertyLinkID", title: "Property Detail ID", width: 100, hidden: true });
                            columnsConfig.push({ field: "PropertyDetailCode", title: "Property Detail Code", width: 200, hidden: true });
                            columnsConfig.push({ field: "PropertyDetailName", title: "Detail", width: 270});


                    $("#gridDetail").data("kendoGrid").setOptions({
                        columns: columnsConfig
                    });
               
               gridDetail.dataSource.read();
               gridDetail.table.on("click", ".check-box" , updateLink);
           }
            
           function UpdatePropertyLink(insert)
           {
                               $.ajax({
                        type: "POST",
                        url: "Item-Property-Link.aspx/UpdateItemPropertyLink",
                        data: JSON.stringify({
                            oItemPropertyLink: JSON.stringify(oItemPropertyLink),
                            isInsert: insert
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
           }
           function updateAll(cb)
           {
           var oTest=[];
            var checked = cb.checked
             var items = $("#gridDetail").data("kendoGrid").dataSource.data();
            for (i = 0; i < items.length; i++) {
              oItemPropertyLink = {};
                var item = items[i];
                    if(checked)
                    {
                        isInsert = true;
                    }
                    else
                    {
                        isInsert = false;   
                    }
                
                    oItemPropertyLink.ItemID = itemID;
                    oItemPropertyLink.PropertyDetailID = item.PropertyDetailID
                     oTest.push(oItemPropertyLink);
                 
                        item.set('PropertyLinkID', checked);
                  }
                     //Update or Insert
                        $.ajax({
                        type: "POST",
                        url: "Item-Property-Link.aspx/UpdateItemPropertyLinks",
                        data: JSON.stringify({
                            oItemPropertyLink: JSON.stringify(oTest),
                            isInsert: checked
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
           }
        $(document).ready(function () {
         
            //Load Grid
            grid = $("#grid").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                           type: "GET",
                            url: "Item-Property.aspx/GetItemPropertys",
                            data: '',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                        },
                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },
                    type: "odata", //Important!!!!
                    schema: {
                        data: "d.Data",
                        total: "d.Count",
                        model: {
                            id: "PropertyID",
                            fields: {
                                PropertyID: { type: "string" },
                                PropertyCode: { type: "string" },
                                PropertyName: { type: "string" }
                            }
                        }
                    }
                },
                change: onChange,
                sortable: true,
                resizable: true,
                height: 420,
                selectable: "row",
                toolbar: [ { name: 'excel'}],
                excel: {
                    fileName: "Item Property List.xlsx",
                    filterable: true
                },
                batch: true,
                columns: [
                            { field: "PropertyID", title: "Property ID", width: 100, hidden: true },
                            { field: "PropertyCode", title: "Property Code", width: 200, hidden: true },
                            { field: "PropertyName", title: "Property", width: 320}
                            ]
            }).data("kendoGrid");

              //Load Grid
             
            gridDetail = $("#gridDetail").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                           type: "GET",
                            url: "Item-Property-Link.aspx/GetItemPropertyLinkByItem",
                            data: '',
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"
                        },
                          parameterMap: function (data, operation) {
                            if (operation === "read") {
                                return {  itemID:itemID ,propertyID: propertyForDetailID };
                            }
                          
                        },
                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },
                    requestEnd: function(e) {
                        if (e.type != undefined ) {
                            if ( e.type === 'read' ) {
                            }
                        }                            
                    },     
                    type: "odata", //Important!!!!
                    schema: {
                        data: "d.Data",
                        total: "d.Count",
                        model: {
                            id: "PropertyID",
                            fields: {
                                PropertyID: { type: "string" },
                                PropertyCode: { type: "string" },
                                PropertyName: { type: "string" }
                            }
                        }
                    }
                },
                dataBound: onDataBound,
                sortable: true,
                resizable: true,
                height: 420,
//                selectable: "row",
                toolbar: [ { name: 'excel'}],
                excel: {
                    fileName: "Customer Property Detail List.xlsx",
                    filterable: true
                },
                batch: true,
                columns: [{ title: '', headerTemplate: '<input type="checkbox" id="checkAll" onclick="updateAll(this)"/>', template: "<input type='checkbox'  class='check-box'  #= PropertyLinkID ? 'checked=checked' : '' # enabled='' />" ,width:50 },
                            { field: "PropertyDetailID", title: "Property Detail ID", width: 100, hidden: true },
                             { field: "PropertyLinkID", title: "Property Detail ID", width: 100, hidden: true },
                            { field: "PropertyDetailCode", title: "Property Detail Code", width: 200, hidden: true },
                            { field: "PropertyDetailName", title: "Detail", width: 270}
                            ]
            }).data("kendoGrid");
             //bind click event to the checkbox
        gridDetail.table.on("click", ".check-box" , updateLink);
        //onDataBound
        function onDataBound(e) {
			var view = this.dataSource.view();
            var count  = view.length;
            var checkCount =0;
			for(var i = 0; i < view.length;i++){
            var  dataItem = view[i];
            if(dataItem.PropertyLinkID!="")
            {

                        checkCount++;
                         this.tbody.find("tr[data-uid='" + view[i].uid + "']")
						.addClass("k-state-selected")
						.find(".checkbox")
						.attr("checked","checked");
		        }
			}		
            if(count == checkCount && count >0)
            {
                 $("#checkAll").prop("checked", true);
            }
            else{
             $("#checkAll").prop("checked", false);

            }
		}
        $("#showSelection").bind("click", function () {
            var checked = [];
            for(var i in checkedIds){
                if(checkedIds[i]){
                    checked.push(i);
                }
            }
        });
    

        
    //on click of the checkbox:
    function selectRow() {
    
        var checked = this.checked,
        row = $(this).closest("tr"),
        dataItem = gridDetail.dataItem(row);
        checkedIds[dataItem.id] = checked;
        if (checked) {
            //-select the row
            row.addClass("k-state-selected");
            } else {
            //-remove selection
            row.removeClass("k-state-selected");
        }
    }
        });
    </script>
    <h2>
        Item Code:&nbsp;
        <asp:Label ID="lblItemCode" runat="server"></asp:Label>
        - Item Name:
        <asp:Label ID="lblItemName" runat="server"></asp:Label>
        <asp:HiddenField ID="lblItemID" runat="server"></asp:HiddenField>
    </h2>
    <hr />
    <table>
        <tr>
            <td>
                <div id="grid">
                </div>
            </td>
            <td>
                <div id="gridDetail">
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="right">
                <div class="k-edit-buttons k-state-default">
                    <a class="k-button k-button-icontext k-grid-cancel" href="#" id="btnClose" onclick="closeLink();">
                        <span class="k-icon k-cancel"></span>Close</a>
                </div>
            </td>
        </tr>
    </table>
</asp:Content>
